<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>患者信息管理</span>
          <div class="header-operations">
            <el-input
              v-model="searchQuery"
              placeholder="搜索患者姓名"
              style="width: 200px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch"></el-button>
              </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">添加患者</el-button>
          </div>
        </div>
      </template>
      <div class="card-body">
        <el-table :data="patientList" style="width: 100%" v-loading="loading">
          <el-table-column prop="userId" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="scope">
              {{ scope.row.gender === 1 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" width="80" />
          <el-table-column prop="phone" label="手机号码" width="120" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="createTime" label="注册时间" width="160" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑患者对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
      <el-form :model="patientForm" :rules="rules" ref="patientFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="patientForm.username" :disabled="editMode"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editMode">
          <el-input v-model="patientForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="patientForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="patientForm.age" :min="1" :max="120"></el-input-number>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="patientForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="patientForm.email"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="patientForm.address" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listUser, addUser, updateUser, delUser } from '@/api/user'

const loading = ref(false)
const searchQuery = ref('')
const patientList = ref([])
const dialogVisible = ref(false)
const editMode = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const patientFormRef = ref(null)

const patientForm = reactive({
  userId: null,
  username: '',
  password: '',
  gender: 1,
  age: 30,
  phone: '',
  email: '',
  address: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => {
  return editMode.value ? '编辑患者信息' : '添加患者'
})

const getList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value || undefined
    }
    const res = await listUser(params)
    patientList.value = res
    total.value = res.length
  } catch (e) {
    patientList.value = []
    total.value = 0
  }
  loading.value = false
}

const handleSearch = () => {
  // 实现搜索逻辑
  console.log('搜索:', searchQuery.value)
  currentPage.value = 1
  getList()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

const resetForm = () => {
  patientForm.userId = null
  patientForm.username = ''
  patientForm.password = ''
  patientForm.gender = 1
  patientForm.age = 30
  patientForm.phone = ''
  patientForm.email = ''
  patientForm.address = ''
}

const handleAdd = () => {
  editMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  editMode.value = true
  Object.assign(patientForm, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除患者 ${row.username} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await delUser(row.userId)
      ElMessage.success('删除成功')
      getList()
    })
    .catch(() => {})
}

const submitForm = () => {
  patientFormRef.value.validate(async (valid) => {
    if (valid) {
      if (editMode.value) {
        await updateUser(patientForm)
        ElMessage.success('患者信息修改成功')
      } else {
        await addUser(patientForm)
        ElMessage.success('患者添加成功')
      }
      dialogVisible.value = false
      getList()
    } else {
      return false
    }
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
